package pojo

import "fmt"

type Node1 struct {
	pass  int
	end   int
	nexts []*Node1
}

func NewNode1() *Node1 {
	return &Node1{pass: 0, end: 0, nexts: make([]*Node1, 26)}
}

type PreTrie struct {
	root *Node1
}

func NewPreTrie() *PreTrie {
	return &PreTrie{root: NewNode1()}
}

func (T *PreTrie) Insert(Str string) {
	if Str == "" {
		return
	}
	bytes := []byte(Str)
	node := T.root
	node.pass++
	for index, value := range bytes {

		i := value - 'a'
		if node.nexts[i] == nil {
			node.nexts[i] = NewNode1()
		}
		node.nexts[i].pass++

		node = node.nexts[i]
		if index == len(bytes)-1 {
			node.end++
		}
	}

}

func (T *PreTrie) Search(Str string) bool {

	if Str == "" {
		return false
	}
	bytes := []byte(Str)
	node := T.root

	for index, value := range bytes {

		i := value - 'a'
		if node.nexts[i] == nil {
			fmt.Println("这个字符串不存在")
			return false
		}

		node = node.nexts[i]
		if index == len(bytes)-1 && node.end != 0 {
			fmt.Println("这个字符串存在", "存在", node.end, "个")
			return true
		}
	}
	return false
}

func (T *PreTrie) Delete(Str string) {
	if !T.Search(Str) {
		return
	}
	bytes := []byte(Str)
	node := T.root

	for index, value := range bytes {

		i := value - 'a'
		node.nexts[i].pass--
		if node.nexts[i].pass == 0 {
			node.nexts[i] = nil
			return
		}

		node = node.nexts[i]
		if index == len(bytes)-1 && node.end != 0 {
			node.end--
		}
	}

}

func (T *PreTrie) PreNumber(Str string) int {
	bytes := []byte(Str)
	node := T.root

	for index, value := range bytes {

		i := value - 'a'
		if node.nexts[i] == nil {
			return 0
		}
		node = node.nexts[i]
		if index == len(bytes)-1 {
			return node.pass
		}
	}
	return 0
}
